package controller

import (
	"admin/model"

	"github.com/gin-gonic/gin"
)

// 获取
func AddDepartment(ctx *gin.Context) {
	modelNew := &model.Department{}
	ctx.ShouldBind(modelNew)
	err := db.Create(modelNew).Error
	if err != nil {
		ctx.JSON(200, gin.H{
			"code":    400,
			"message": "添加失败",
		})
		return
	}
	ctx.JSON(200, gin.H{
		"code":    200,
		"message": "添加成功",
	})
}

// 获取
func GetDepartment(ctx *gin.Context) {
	var modelNews []model.Department
	db.Find(&modelNews)
	ctx.JSON(200, gin.H{
		"code":    200,
		"message": "获取成功",
		"data":    modelNews,
	})
}

// 删除
func DelDepartment(ctx *gin.Context) {
	type DeleteField struct {
		Id int `json:"id"`
	}
	deleteField := DeleteField{}
	bindErr := ctx.ShouldBind(&deleteField)
	if bindErr != nil {
		ctx.JSON(200, gin.H{
			"code":    400,
			"message": "数据格式错误",
		})
		return
	}
	err := db.Where("id = ?", deleteField.Id).Unscoped().Delete(new(model.Department)).Error
	if err != nil {
		ctx.JSON(200, gin.H{
			"code":    400,
			"message": "删除失败",
		})
		return
	}
	ctx.JSON(200, gin.H{
		"code":    200,
		"message": "删除成功",
	})
}

// 更新
func PutDepartment(ctx *gin.Context) {
	type DeleteField struct {
		Id   int              `json:"id"`
		Data model.Department `json:"data"`
	}
	deleteField := DeleteField{}
	ctx.ShouldBind(&deleteField)
	err := db.Where("id = ?", deleteField.Id).Debug().Updates(deleteField.Data).Error
	if err != nil {
		ctx.JSON(200, gin.H{
			"code":    400,
			"message": "更新失败,确认此记录姓名不能重复",
		})
		return
	}
	ctx.JSON(200, gin.H{
		"code":    200,
		"message": "更新成功",
	})
}
